package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Set;

/*
类简介：

功能：

时间：2020/4/9

*/
@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        System.out.println("=============username = " + username);

        User user = userService.findByUsername(username);

        //查不到用户时，返回空
        if (user == null){
            return null;
        }

        System.out.println("user = " + user);

        Set<Role> roles = user.getRoles();

        if (roles != null){

            ArrayList<GrantedAuthority> list = new ArrayList<>();

            //遍历所有角色，把角色的关键字赋给list
            for (Role role : roles) {
                list.add(new SimpleGrantedAuthority(role.getKeyword()));

                //遍历角色的所有权限，把权限的关键字赋给list
                Set<Permission> permissions = role.getPermissions();
                if (permissions != null){
                    for (Permission permission : permissions) {
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
            return new org.springframework.security.core.userdetails.User(
                    username,user.getPassword(),list
            );

        }



        return new org.springframework.security.core.userdetails.User(
                username,user.getPassword(),new ArrayList<>()
        );
    }
}
